package yhao.demo.autocode.core.sqlmapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import yhao.demo.autocode.core.sqlmapper.connect.DbConnectParam;
import yhao.demo.autocode.core.sqlmapper.connect.DbConnectionUtil;
import yhao.demo.autocode.core.sqlmapper.connect.SchemeInfo;
import yhao.demo.autocode.core.sqlmapper.connect.SqlModelDef;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class SqlToDocxHelper {
    //数据库连接
    private DbConnectParam dbParam;
    //数据库名
    private String dbName;
    //表名
    private String tableName;
    public final static String CONF_DIR_PATH =
            System.getProperty("user.home") + File.separator + "yhao.sqlTodocx";
    /**
     * @param dbParam      数据库连接
     * @param dbName       数据库名
     * @param tableName    表名
     */
    public SqlToDocxHelper(DbConnectParam dbParam, String dbName, String tableName) {
        this.dbParam = dbParam;
        this.dbName = dbName;
        this.tableName = tableName;
    }

    public void doMapper() throws Exception {
        Resource resource = new ClassPathResource("sqlToDocx/template.docx");
        //读取文档内容
        XWPFDocument document = new XWPFDocument(resource.getInputStream());
        XWPFTable root = document.getTables().get(0);
        System.out.println(toString());
        SchemeInfo scheme = DbConnectionUtil.getAllSchemeInfo(dbParam,dbName,tableName);
        List<SqlModelDef> defs = scheme.getDefList();
        System.out.println("开始生成数据库描述表格...");
        //设置表名
        String title = (StringUtils.isNotEmpty(dbName)?dbName+".":"")+tableName;
        if(StringUtils.isNotEmpty(scheme.getTableDesc())){
            title = title+"("+scheme.getTableDesc()+")";
        }
        root.getRows().get(0).getCell(1).setText(title);
        int columnSize =  root.getRows().get(2).getTableCells().size();
        int rowNum = 2;
        for(int i=0;i<defs.size();i++){
            if(i!=0){
                addNewRow(root,columnSize);
            }
            SqlModelDef def = defs.get(i);
            XWPFTableRow row = root.getRow(rowNum);
            row.getCell(0).setText(def.getColumnName());
            row.getCell(1).setText(def.getColumnType());
            row.getCell(2).setText(def.isPrimaryKey()?"√":"");
            row.getCell(3).setText(!def.isCanNull()?"√":"");
            row.getCell(4).setText(def.isIndexKey()?"√":"");
            row.getCell(5).setText(def.getColumnComment());
            rowNum++;
        }
        makeFile(document);
        System.out.println("开始生成数据库描述表格...DONE");
        System.out.println();
        System.out.println("完成操作...");
        System.out.println("请到以下地址复制文件..." + CONF_DIR_PATH);
    }

    private void makeFile(XWPFDocument document) throws IOException {
        File root = new File(CONF_DIR_PATH);
        if (!root.exists()) {
            root.mkdir();
        }
        File file = new File(CONF_DIR_PATH + File.separator + tableName + ".docx");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        document.write(new FileOutputStream(file));
    }

    private void addNewRow(XWPFTable root,int colSize) {
        XWPFTableRow targetRow = new XWPFTableRow(root.getCTTbl().addNewTr(),root);
        for (int i = 0; i < colSize; i++) {
            targetRow.createCell();
        }
        root.getRows().add(targetRow);
    }

    @Override
    public String toString() {
        return "SqlToDocxHelper{" +
                "dbParam=" + dbParam +
                ", dbName='" + dbName + '\'' +
                ", tableName='" + tableName + '\'' +
                '}';
    }
}
